package com.example.permissionsystem1_1.businessFunction.service.interfaces.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.permissionsystem1_1.businessFunction.dao.entity.po.*;
import com.example.permissionsystem1_1.businessFunction.dao.repository.*;
import com.example.permissionsystem1_1.businessFunction.service.converter.RoleInfoServiceConverter;
import com.example.permissionsystem1_1.businessFunction.service.entity.reqModel.roleInfoReqModel.*;
import com.example.permissionsystem1_1.businessFunction.service.entity.rspModel.roleInfoRspModel.*;
import com.example.permissionsystem1_1.businessFunction.service.interfaces.RoleInfoService;
import com.example.permissionsystem1_1.common.businessFunction.BaseServiceImpl;
import com.example.permissionsystem1_1.system.annotation.aspectAnnotation.SuperManageOperationAspectAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

@Service
public class RoleInfoServiceImpl extends BaseServiceImpl implements RoleInfoService {
    @Autowired
    private RoleInfoDao roleInfoDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private RoleFunctionDao roleFunctionDao;
    @Autowired
    private UserFunctionRecordDao userFunctionRecordDao;
    @Autowired
    private FunctionInfoDao functionInfoDao;

    @Override
    public RoleInfoInsertRspModel insert(RoleInfoInsertReqModel reqModel) {
        RoleInfoPo po= RoleInfoServiceConverter.convertReqModelToPo(reqModel);
        Integer resultInt=-1;
        //字段重复性校验:如果重复,则会将po变成空,从而阻止接下去的数据库操作
        List<String> fieldNames=new ArrayList<>();
        fieldNames.add("roleName");
        fieldNames.add("roleCode");
        try {
            po=fieldsRepeatCheck(roleInfoDao,"selects",po,fieldNames,"insert");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            po=null;
        }

        if(po!=null){
            resultInt=roleInfoDao.insert(po);
        }
        return RoleInfoServiceConverter.covertToRspModel(resultInt);
    }

//    @Override
//    public TestInsertBatchRspModel insertBatch(TestInsertBatchReqModel reqModel) {
//        List<TestPo> pos=TestServiceConverter.convertReqModelToPo(reqModel);
//        Integer resultSum=-1;
//        if(pos!=null&&pos.size()>0){
//            resultSum=testDao.insertBatch(pos);
//        }
//        return TestServiceConverter.covertToInsertBatchRspModel(resultSum);
//    }

    @Override
    @Transactional
    @SuperManageOperationAspectAnnotation
    public RoleInfoDeleteByIdRspModel deleteById(RoleInfoDeleteByIdReqModel reqModel) {
        RoleInfoPo po= RoleInfoServiceConverter.convertReqModelToPo(reqModel);
        //关联数据清理:根据角色id删除当前角色的用户角色关联记录和角色功能关联记录
        deleteUserRoleAndRoleFunctionByRoleId(po.getId());
        //功能权限的重建:根据用户id删除用户功能的全部功能
        reconstructionUserFunctionsByRoleId(po.getId());
        return RoleInfoServiceConverter.covertToDeleteByIdRspModel(roleInfoDao.deleteById(po.getId()));
    }

//    @Override
//    public TestDeletesRspModel deletes(TestDeletesReqModel reqModel) {
//        TestPo po= TestServiceConverter.convertReqModelToPo(reqModel);
//        Integer resultSum=-1;
//        if(po!=null){
//            resultSum=testDao.deletes(po);
//        }
//        return TestServiceConverter.covertToDeletesRspModel(resultSum);
//    }

//    @Override
//    public TestDeleteBatchByIdsRspModel deleteBatchByIds(TestDeleteBatchByIdsReqModel reqModel) {
//        TestPo po=TestServiceConverter.convertReqModelToPo(reqModel);
//        Integer resultSum=-1;
//        if(po!=null&&po.getIds()!=null&&po.getIds().size()>0){
//            resultSum=testDao.deleteBatchByIds(po.getIds());
//        }
//        return TestServiceConverter.covertToDeleteBatchByIdsRspModel(resultSum);
//    }

    @Override
    @SuperManageOperationAspectAnnotation
    public RoleInfoUpdateByIdRspModel updateById(RoleInfoUpdateByIdReqModel reqModel) {
        RoleInfoPo po= RoleInfoServiceConverter.convertReqModelToPo(reqModel);
        Integer resultInt=-1;
        //字段重复性校验:如果重复,则会将po变成空,从而阻止接下去的数据库操作
        List<String> fieldNames=new ArrayList<>();
        fieldNames.add("roleName");
        fieldNames.add("roleCode");
        try {
            po=fieldsRepeatCheck(roleInfoDao,"selects",po,fieldNames,"update");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            po=null;
        }
        if(po!=null){
            resultInt=roleInfoDao.updateById(po);
        }
        return RoleInfoServiceConverter.covertToUpdateByIdRspModel(resultInt);
    }

//    @Override
//    public TestUpdatesRspModel updates(TestUpdatesReqModel reqModel) {
//        TestPo po= TestServiceConverter.convertReqModelToPo(reqModel);
//        Integer resultSum=-1;
//        if(po!=null&&po.getByPo()!=null&&po.getSetPo()!=null){
//            resultSum=testDao.updates(po.getByPo(),po.getSetPo());
//        }
//        return TestServiceConverter.covertToUpdatesRspModel(resultSum);
//    }

//    @Override
//    public TestUpdateBatchByIdsRspModel updateBatchByIds(TestUpdateBatchByIdsReqModel reqModel) {
//        TestPo po= TestServiceConverter.convertReqModelToPo(reqModel);
//        Integer resultSum=-1;
//        if(po!=null&&po.getIds()!=null&&po.getIds().size()>0){
//            resultSum=testDao.updateBatchByIds(po);
//        }
//        return TestServiceConverter.covertToUpdateBatchByIdsRspModel(resultSum);
//    }

    @Override
    @SuperManageOperationAspectAnnotation
    public RoleInfoSelectByIdRspModel selectById(RoleInfoSelectByIdReqModel reqModel) {
        RoleInfoPo po= RoleInfoServiceConverter.convertReqModelToPo(reqModel);
        if(po!=null&&po.getId()!=null){
            po=roleInfoDao.selectById(po.getId());
        }
        return RoleInfoServiceConverter.covertToSelectByIdRspModel(po);
    }

    @Override
    public RoleInfoSelectsRspModel selects(RoleInfoSelectsReqModel reqModel) {
        RoleInfoPo po= RoleInfoServiceConverter.convertReqModelToPo(reqModel);
        List<RoleInfoPo> pos=new ArrayList<>();
        if(po!=null){
            pos=roleInfoDao.selects(po);
        }
        return RoleInfoServiceConverter.covertToSelectsModel(pos);
    }

//    @Override
//    public TestSelectBatchByIdsRspModel selectBatchByIds(TestSelectBatchByIdsReqModel reqModel) {
//        TestPo po= TestServiceConverter.convertReqModelToPo(reqModel);
//        List<TestPo> pos=new ArrayList<>();
//        if(po!=null){
//            pos=testDao.selectBatchByIds(po.getIds());
//        }
//        return TestServiceConverter.covertToSelectBatchByIdsModel(pos);
//    }

    @Override
    public RoleInfoSelectPageRspModel selectPage(RoleInfoSelectPageReqModel reqModel) {
        RoleInfoPo po=RoleInfoServiceConverter.convertReqModelToPo(reqModel);
        if(po==null){
            return null;
        }
        Page page=new Page(reqModel.getPageNo(),reqModel.getPageSize());
        //默认按照年龄排序
        page.addOrder(OrderItem.asc("id"));
        IPage<RoleInfoPo> iPagePo=roleInfoDao.selectPage(page,po);
        return RoleInfoServiceConverter.covertToSelectPageModel(iPagePo);
    }

    //**********本类的业务处理方法
    /** 关联数据清理:根据角色id删除当前角色的用户角色关联记录和角色功能关联记录 */
    private void deleteUserRoleAndRoleFunctionByRoleId(Long roleId){
        UserRolePo userRolePo=new UserRolePo();
        userRolePo.setRoleId(roleId);
        userRoleDao.deletes(userRolePo);
        RoleFunctionPo roleFunctionPo=new RoleFunctionPo();
        roleFunctionPo.setRoleId(roleId);
        roleFunctionDao.deletes(roleFunctionPo);
    }
    /** 功能权限的重建:根据角色id重建角色下的每个用户的全部用户功能记录 */
    private void reconstructionUserFunctionsByRoleId(Long roleId){
        List<UserRolePo> userRolePos=userRoleDao.selectAllUsersByRoleId(roleId);
        if(userRolePos==null||userRolePos.size()<=0){
            return;
        }
        //对当前角色关联的所有用户,进行功能权限重建
        for (UserRolePo userRolePo:userRolePos) {
            Long userId=userRolePo.getUserId();
            UserFunctionRecordPo userFunctionRecordPo=new UserFunctionRecordPo();
            userFunctionRecordPo.setUserId(userId);
            userFunctionRecordDao.deletes(userFunctionRecordPo);
            List<FunctionInfoPo> functionInfoPos=functionInfoDao.selectsByUserId(userId);
            if(functionInfoPos==null||functionInfoPos.size()<=0){//这个用户没任何功能权限,所以进行下一个用户的功能权限构建
                continue;
            }
            List<UserFunctionRecordPo> userFunctionRecordPos=new ArrayList<>();
            String creator="admin";
            String updator="admin";
            Date now=new Date();
            for (FunctionInfoPo functionInfoPo:functionInfoPos) {
                UserFunctionRecordPo ufrPo=new UserFunctionRecordPo();
                ufrPo.setUserId(userId);
                ufrPo.setFunctionId(functionInfoPo.getId());
                ufrPo.setCreator(creator);
                ufrPo.setCreateTime(now);
                ufrPo.setUpdator(updator);
                ufrPo.setUpdateTime(now);
                userFunctionRecordPos.add(ufrPo);
            }
            userFunctionRecordDao.insertBatch(userFunctionRecordPos);
        }
    }
}
